/*
 * Copyright 2010 Biz-e (info@biz-e.nl)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.gwt.baselib.ui.client.widgets;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.ListBox;

/**
 * Extended {@link ListBox} with some convenience methods.
 * 
 * @author Joost A. Bloemsma
 * 
 */
public class ListBoxEx extends com.google.gwt.user.client.ui.ListBox {
	
	/**
	 * Constructs a new ListBox instance
	 * 
	 * @see com.google.gwt.user.client.ui.ListBox
	 */
	public ListBoxEx() {
		super();
	}
	
	/**
	 * Constructs a new ListBox instance
	 * 
	 * @see com.google.gwt.user.client.ui.ListBox
	 * @param isMultipleSelect
	 */
	public ListBoxEx(boolean isMultipleSelect) {
		super(isMultipleSelect);
	}
	
	/**
	 * Constructs a new ListBox instance
	 * 
	 * @see com.google.gwt.user.client.ui.ListBox
	 * @param element
	 */
	public ListBoxEx(Element element) {
		super(element);
	}
	
	/**
	 * Returns the text of the selected item
	 * 
	 * @param text
	 */
	public void selectText(String text) {
		int i = getTextIndex(text);
		if (i > -1)
			setSelectedIndex(i);
	}
	
	/**
	 * Returns the index of the passed text
	 * 
	 * @param text
	 * @return -1 if not found
	 */
	public int getTextIndex(String text) {
		for (int i = 0; i < this.getItemCount(); i++) {
			if (this.getItemText(i).equals(text)) {
				return i;
			}
		}
		return -1;
	}
	
	/**
	 * Returns the value of the selected item
	 * 
	 * @param value
	 */
	public void selectValue(String value) {
		int i = getValueIndex(value);
		if (i > -1)
			setSelectedIndex(i);
	}
	
	/**
	 * Returns the index of the passed value
	 * 
	 * @param value
	 * @return -1 if not found
	 */
	public int getValueIndex(String value) {
		for (int i = 0; i < this.getItemCount(); i++) {
			if (this.getValue(i).equals(value)) {
				return i;
			}
		}
		return -1;
	}
	
	/**
	 * Convenience method for {@code getItemText(getSelectedIndex())}
	 * 
	 * @return text
	 */
	public String getSelectedText() {
		return this.getItemText(getSelectedIndex());
	}
	
	/**
	 * Convenience method for {@code getValue(getSelectedIndex())}
	 * 
	 * @return value
	 */
	public String getSelectedValue() {
		return this.getValue(getSelectedIndex());
	}
	
	public void addItem(String text, Object object) {
		this.addItem(text);
	}
}
